import useForm from "@module/useForm";
import Input from "@ui/RJMart/input";
import Icon from "@ui/RJMart/icons";
import RobinFilter from "@module/RobinFilter";
import message from "@ui/RJMart/message";
import img0 from "../../../imgs/ic_email.png";

export default function StepTwo() {
    const params = $state.params;
    const { registerType, findWay, account } = params || {};

    function doSubmit() {
        console.log(formData);

        if (!formData.code) {
            updateFormData({
                $$status: { code: "请输入验证码" }
            });
            return false;
        }

        const isValid = formData.$$valid;
        if (isValid) {
            // ZenUI.SL(60);
            let vftUrl = "/store/api/user/buyer/ForgotPasswordByMobile";
            if (params.registerType == 2) {
                vftUrl = "/suppliers/anon/ForgotPasswordByMobile";
            }
            let vftData = {
                mobile: params.account,
                pin: formData.code
            };
            REST.post(vftUrl, vftData, "dis").then(
                function(data) {
                    // ZenUI.HL();
                    console.log(data);
                    if (data.code == "0000") {
                        doStepTwo(data.token);
                    } else {
                        // alert(data.message);
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    }
                },
                function(error) {
                    // ZenUI.HL();
                    console.log(error);
                }
            );
        }
    }

    function doStepTwo(token) {
        $state.go({
            stateName: "/forgetpwd",
            params: {
                step: 3,
                account: params.account,
                token: token,
                registerType: params.registerType,
                forgetPwd: 1
            }
        });
    }

    function sendAgain() {
        ZenUI.SL(60);
        let sendUrl = "/store/api/user/buyer/ForgotPasswordByEmail";
        if (params.registerType == 2) {
            sendUrl = "/suppliers/anon/ForgotPasswordByEmail";
        }
        let sendData = {
            account: params.account
        };
        REST.post(sendUrl, sendData, "noInfo").then(
            function(data) {
                ZenUI.HL();
                console.log(data);
                if (data.code == "0000") {
                    message.info("邮件已重发成功，请查收！");
                }
            },
            function(error) {
                ZenUI.HL();
                console.log(error);
            }
        );
    }

    const [stateObj, updateState] = usePartState({
        canClickVerifyBtn: true
    });

    const {
        formData,
        handleChange,
        handleSubmit,
        updateFormData,
        validations,
        addValidate,
        addValidateMulti
    } = useForm(
        doSubmit,
        { account: params.account, registerType: params.registerType },
        "findPwdFormStep2"
    );

    addValidateMulti({
        code: [RobinFilter.verifyCodeValidate]
    });

    function beforeHandleChange(event) {
        handleChange(event);
        // console.log(formData)
    }

    return (
        <div className={"regi-step-two"}>
            {params.findWay == 1 && (
                <form className={"regi-content-form"} name={"findPwdFormStep2"}>
                    <InputItemForVerifyCode
                        name={"code"}
                        title={"手机验证码"}
                        placeholder={"请输入验证码"}
                        handleChange={beforeHandleChange}
                        formData={formData}
                        index={3}
                        canClickVerifyBtn={stateObj.canClickVerifyBtn}
                        updateFormData={updateFormData}
                    />

                    <NextStep formData={formData} doSubmit={doSubmit} />
                </form>
            )}
            {params.findWay == 2 && (
                <form className={"regi-content-form"} name={"findPwdFormStep2"}>
                    <div className={"regi-step2-top"}>
                        <img
                            src={img0}
                            className="zen_il-bl zen_w-56 zen_h-56 zen_m-h-30 zen_m-v-10"
                        />
                        <div className={"regi-step2-top-txt"}>
                            <p>密码重置邮件已发送</p>
                            <p
                                className={"regi-step2-email"}
                            >{`密码重置邮件已发送至你的注册邮箱：${
                                params.account
                            }`}</p>
                        </div>
                    </div>
                    <div className={"regi-step2-bottom"}>
                        <p className={"zen_fs-18 zen_3C3C3C"}>没有收到邮件？</p>
                        <p
                            className={
                                "zen_969696 zen_fs-12 zen_l-h-16 zen_m-t-20"
                            }
                        >
                            1. 请检查邮箱地址是否正确，你可以返回
                            <span
                                onClick={() => {
                                    $state.go({
                                        stateName: "/forgetpwd",
                                        params: {
                                            step: 1,
                                            forgetPwd: 1
                                        }
                                    });
                                }}
                                className={"zen_0094EB zen_cur-p"}
                            >
                                重新填写
                            </span>
                        </p>
                        <p
                            className={
                                "zen_969696 zen_fs-12 zen_l-h-16 zen_m-t-10"
                            }
                        >
                            2. 检查你的邮件垃圾箱
                        </p>
                        <p
                            className={
                                "zen_969696 zen_fs-12 zen_l-h-16 zen_m-t-10"
                            }
                        >
                            3. 若仍未收到确认，请尝试
                            <span
                                onClick={sendAgain}
                                className={"zen_0094EB zen_cur-p"}
                            >
                                重新发送
                            </span>
                        </p>
                    </div>
                </form>
            )}
        </div>
    );
}

let unclickable = false;
function InputItemForVerifyCode(props) {
    const [stateObj, updateState] = usePartState({
        verifyTxt: "获取验证码",
        hasTimer: false
    });
    const {
        title,
        placeholder,
        index,
        handleChange,
        name,
        canClickVerifyBtn,
        updateFormData
    } = props;
    let formData = props.formData;

    function addName() {
        let inputEle = document.querySelector(
            `.regi-inputs-input>div[name=${name}] input`
        );
        if (inputEle) {
            inputEle.setAttribute("name", name);
        }
    }

    React.useEffect(() => {
        addName();
    }, []);

    let timerId = null;
    function getVerifycode() {
        /*const isValid =
            formData.$$status.hasOwnProperty("phone") &&
            !formData.$$status["phone"]
                ? true
                : false;*/
        const hasPhone = formData.account ? true : false;

        if (unclickable) {
            updateFormData({
                $$status: { code: "手机验证码请求太频繁，请稍后再试" }
            });
            return false;
        }

        if (hasPhone) {
            let codeUrl = "/store/api/system/PinRequest";
            let codeData = {
                mobile: formData.account,
                useraction: "BuyerForgetPsw"
            };
            if (formData.registerType == 2) {
                codeUrl = "/suppliers/anon/pinRequest";
                codeData.useraction = "SuppForgetPsw";
            }
            REST.post(codeUrl, codeData, "dis").then(
                function(data) {
                    console.log(data);
                    if (data.code == "0000") {
                        console.log("获取验证码成功");
                        countDown(); //倒计时
                    } else if (data.code == "1012" || data.code == "1013") {
                        unclickable = true;
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    } else {
                        // alert(data.message);
                        updateFormData({
                            $$status: { code: data.message }
                        });
                    }
                },
                function(error) {
                    console.log(error);
                }
            );
        }
    }

    function countDown() {
        let seconds = 60;
        updateState({
            verifyTxt: `剩 ${seconds} 秒`,
            hasTimer: true
        });
        timerId = setInterval(() => {
            if (seconds <= 1) {
                updateState({
                    verifyTxt: `获取验证码`,
                    hasTimer: false
                });
                clearInterval(timerId);
                return;
            }
            seconds--;
            updateState({
                verifyTxt: `剩 ${seconds} 秒`,
                hasTimer: true
            });
        }, 1000);
    }

    const isValid =
        formData.$$status.hasOwnProperty(name) && formData.$$status[name]
            ? false
            : true;

    return (
        <div className={"regi-content-inputs"}>
            <div
                className={
                    index == 3
                        ? "regi-step3-label-box2"
                        : "regi-step3-label-box"
                }
            >
                <span className={"regi-content-label"}>{title}</span>
            </div>
            <div className={"regi-inputs-input"}>
                <Input
                    name={name}
                    placeholder={placeholder}
                    onChange={handleChange}
                    error={!isValid}
                    statusIcon={
                        isValid ? null : (
                            <Icon
                                type="exclamation-circle-fill"
                                color="error"
                                width="18.26px"
                                height="18.26px"
                            />
                        )
                    }
                />
                {canClickVerifyBtn ? (
                    <div
                        onClick={stateObj.hasTimer ? () => {} : getVerifycode}
                        className={
                            stateObj.hasTimer
                                ? "regi-step3-veri3"
                                : "regi-step3-veri2"
                        }
                    >
                        <p>{stateObj.verifyTxt}</p>
                    </div>
                ) : (
                    <div className={"regi-step3-veri"}>
                        <p>获取验证码</p>
                    </div>
                )}

                {!isValid && (
                    <p className={"regi-content-error-tip"}>
                        {formData.$$status[name]}
                    </p>
                )}
            </div>
        </div>
    );
}

function NextStep(props) {
    const { doSubmit, formData } = props;
    const isValid = formData.$$valid;
    return (
        <div
            onClick={doSubmit}
            className={
                isValid ? "regi-content-next-step" : "regi-content-next-step1"
            }
        >
            <p>下一步</p>
        </div>
    );
}
